package top.frsf.mqttconsumerapp.config;

import lombok.extern.slf4j.Slf4j;
import org.eclipse.paho.client.mqttv3.MqttClient;
import org.eclipse.paho.client.mqttv3.MqttConnectOptions;
import org.eclipse.paho.client.mqttv3.MqttException;
import org.eclipse.paho.client.mqttv3.persist.MemoryPersistence;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Configuration;
import top.frsf.mqttconsumerapp.callback.MqttConsumerCallback;

import javax.annotation.PostConstruct;

@Slf4j
@Configuration
public class MqttConsumerConfig {

    @Value("${mqtt.url}")
    private String url;

    @Value("${mqtt.username}")
    private String username;

    @Value("${mqtt.password}")
    private String password;

    @Value("${mqtt.client.id}")
    private String clientId;

    @Value("${mqtt.default.topic}")
    private String defaultTopic;

    private MqttClient client;

    @PostConstruct
    public void init() {
        connect();
    }

    /**
     * 配置Mqtt客户端对象
     */
    public void connect() {
        try {
            client = new MqttClient(url, clientId, new MemoryPersistence());
            MqttConnectOptions options = new MqttConnectOptions();
            options.setCleanSession(true);
            options.setUserName(username);
            options.setPassword(password.toCharArray());
            //连接超时，单位为秒
            options.setConnectionTimeout(100);
            //设置心跳时间 单位为秒，表示服务器每隔 1.5*20秒的时间向客户端发送心跳判断客户端是否在线
            options.setKeepAliveInterval(20);
            //设置遗嘱消息的话题，若客户端和服务器之间的连接意外断开，服务器将发布客户端的遗嘱信息
            //QoS服务质量，QoS0至多一次，QoS1至少一次，QoS2只有一次
            options.setWill("willTopic", (clientId + "与服务器断开连接").getBytes(), 0, false);
            client.setCallback(new MqttConsumerCallback());
            client.connect(options);
            //订阅主题 消息等级和主题数组一一对应，服务端将按照指定等级给订阅了主题的客户端推送消息
            int[] qos = {1, 1};
            String[] topics = {"topic1", "topic2"};
            client.subscribe(topics, qos);
        } catch (MqttException e) {
            log.error("Mqtt Server has broken.");
        }
    }

    /**
     * 断开连接
     */
    public void disconnect() {
        try {
            client.disconnect();
        } catch (MqttException e) {
            log.error("Mqtt Server has broken.");
        }
    }
}
